

package com.maoshi.shop.api.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.bean.app.dto.UserCenterInfoDto;
import com.maoshi.shop.bean.app.dto.UserDto;
import com.maoshi.shop.bean.app.param.CheckRegisterSmsParam;
import com.maoshi.shop.bean.app.param.UserInfoParam;
import com.maoshi.shop.bean.app.param.UserRegisterParam;
import com.maoshi.shop.bean.enums.SmsType;
import com.maoshi.shop.bean.model.ShopAuditing;
import com.maoshi.shop.bean.model.ShopDetail;
import com.maoshi.shop.bean.model.User;
import com.maoshi.shop.bean.model.UserExtension;
import com.maoshi.shop.bean.param.UserParam;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.IPHelper;
import com.maoshi.shop.common.util.PrincipalUtil;
import com.maoshi.shop.common.util.RedisUtil;
import com.maoshi.shop.security.api.model.MaoshiUser;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.security.comment.enums.App;
import com.maoshi.shop.security.comment.model.AppConnect;
import com.maoshi.shop.security.comment.token.AuthenticationToken;
import com.maoshi.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;

/**
 * 用户信息
 * @author LGH
 */
@RestController
@RequestMapping("/p/user")
@Api(tags="用户接口")
@AllArgsConstructor
public class UserController {

	private final UserService userService;

	private final MapperFacade mapperFacade;

	private final OrderService orderService;

	private final ShopDetailService shopDetailService;

	private final ShopAuditingService shopAuditingService;

	private final WxMaService wxMaService;

	private final UserExtensionService userExtensionService;



    /**
     * 查看用户接口
     */
    @GetMapping("/userInfo")
    @ApiOperation(value="查看用户信息", notes="根据用户ID（userId）获取用户信息")
    public ResponseEntity<UserDto> userInfo() {
    	String userId = SecurityUtils.getUser().getUserId();
    	User user = userService.getUserByUserId(userId);
		//获取用户等级积分详细表
		UserExtension extension = userExtensionService.getOne(
				new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, SecurityUtils.getUser().getUserId()));
    	UserDto userDto = mapperFacade.map(user, UserDto.class);
		userDto.setLevel(extension.getLevel());
		userDto.setGrowth(extension.getGrowth());
		userDto.setScore(extension.getScore());
		userDto.setLevelType(extension.getLevelType());
		userDto.setBalance(extension.getBalance());
		if(userDto.getUserMobile() != null){
			userDto.setMobile(userDto.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
		}

        return ResponseEntity.ok(userDto);
    }

    @PutMapping("/setUserInfo")
    @ApiOperation(value="设置用户信息", notes="设置用户信息")
    public ResponseEntity<Void> setUserInfo(@RequestBody UserInfoParam userInfoParam) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = new User();
        user.setUserId(userId);
        user.setPic(StrUtil.isBlank(userInfoParam.getAvatarUrl())?null :userInfoParam.getAvatarUrl());
        user.setSex(userInfoParam.getSex() == null?user.getSex():userInfoParam.getSex());
        user.setNickName(userInfoParam.getNickName() == null?user.getNickName():userInfoParam.getNickName());
        user.setUserMobile(userInfoParam.getUserMobile() == null?user.getUserMobile():userInfoParam.getUserMobile());
        user.setBirthDate(userInfoParam.getBirthDate() == null?user.getBirthDate():userInfoParam.getBirthDate());
        user.setUserMail(StrUtil.isNotBlank(userInfoParam.getUserMail())?userInfoParam.getUserMail():user.getUserMail());
        if(StrUtil.isNotBlank(userInfoParam.getNickName())){
            user.setNickName(userInfoParam.getNickName());
        }
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }

	@GetMapping("/centerInfo")
	@ApiOperation(value="个人中心信息", notes="获取用户个人中心信息")
	public ResponseEntity<UserCenterInfoDto> centerInfo() {
		String userId = SecurityUtils.getUser().getUserId();
		UserCenterInfoDto userCenterInfoDto = new UserCenterInfoDto();
		userCenterInfoDto.setOrderCountData(orderService.getOrderCount(userId));

		ShopAuditing shopAuditing = shopAuditingService.getShopAuditingByUserId(userId);

		userCenterInfoDto.setShopAuditStatus(shopAuditing == null ? null : shopAuditing.getStatus());

		ShopDetail shopDetail = shopDetailService.getShopDetailByUserId(userId);

		userCenterInfoDto.setIsSetPassword(shopDetail != null && StrUtil.isNotBlank(shopDetail.getPassword()));

		userCenterInfoDto.setShopId(shopDetail == null ?  null : shopDetail.getShopId());
		return ResponseEntity.ok(userCenterInfoDto);
	}


	@GetMapping("/getPhoneNumber")
	@ApiOperation(value="获取用户绑定手机号", notes="根据小程序的加密数据，iv获取当前用户的手机号")
	public ResponseEntity<WxMaPhoneNumberInfo> getPhoneNumber(@RequestParam String encryptedData, @RequestParam String ivStr) {

		return ResponseEntity.ok(wxMaService.getUserService().getPhoneNoInfo(SecurityUtils.getUser().getSessionKey(), encryptedData, ivStr));
	}

	@GetMapping("/getUserScore")
	@ApiOperation(value="获取用户积分", notes="返回用户的积分信息")
	public ResponseEntity<UserParam> getUserScore() {
		String userId = SecurityUtils.getUser().getUserId();
		User user = userService.getById(userId);
		UserParam userParam = mapperFacade.map(user,UserParam.class);
		System.out.println();
		return ResponseEntity.ok(userParam);
	}

}
